import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'package:flutter/foundation.dart' show kIsWeb;
import '../services/upload/core/upload_manager.dart';
import '../screens/upload_tasks_screen.dart';
import 'dart:async';

class FilePickerButton extends StatelessWidget {
  final UploadManager uploadManager;
  final bool multiple;
  final List<String>? allowedExtensions;
  final FileType fileType;
  final String? dialogTitle;

  const FilePickerButton({
    Key? key,
    required this.uploadManager,
    this.multiple = true,
    this.allowedExtensions,
    this.fileType = FileType.any,
    this.dialogTitle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FloatingActionButton.extended(
      onPressed: () => _pickFiles(context),
      icon: const Icon(Icons.add),
      label: const Text('添加文件'),
    );
  }

  Future<void> _pickFiles(BuildContext context) async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: fileType,
        allowMultiple: multiple,
        allowedExtensions: allowedExtensions,
        dialogTitle: dialogTitle,
      );

      if (result != null) {
        final filePaths =
            result.paths
                .where((path) => path != null)
                .map((path) => path!)
                .toList();

        if (filePaths.isNotEmpty && context.mounted) {
          // 直接使用 UploadManager 的统一处理逻辑
          final tasks = await uploadManager.addFilesUpload(
            filePaths,
            context: context,
          );
        }
      }
    } catch (e) {
      if (!context.mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择文件失败: $e'), backgroundColor: Colors.red),
      );
    }
  }
}
